package com.kczyjg.hybird

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BarUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private val updateUrl = "http://49.233.128.19/M/version.info"
    private lateinit var launcher: ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        BarUtils.transparentStatusBar(this)
        BarUtils.setStatusBarLightMode(this, false)
        init()
    }

    fun init() {
        launcher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult(), {
                UpdateApkHelper.checkUpdate(this, updateUrl, {
                    lifecycleScope.launch {
                        delay(1000)
                        startActivity(Intent(this@MainActivity, H5Activity::class.java))
                        this@MainActivity.finish()
                    }
                })
            })
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val installAllowed = packageManager.canRequestPackageInstalls()
            if (!installAllowed) {

                //跳转到设置界面
                val intent = Intent(
                    Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                    Uri.parse("package:" + getPackageName())
                )
                launcher.launch(intent)
                return
            }
        }
        UpdateApkHelper.checkUpdate(this, updateUrl, {
            lifecycleScope.launch {
                delay(1000)
                startActivity(Intent(this@MainActivity, H5Activity::class.java))
                this@MainActivity.finish()
            }
        })
    }


}